package com.demo.rydemo.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.rydemo.d_user.entity.DUser;
import com.demo.rydemo.d_user.service.IDUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author ry
 * @Description  https://www.jianshu.com/p/f485c756096c
 * @Date 2020/8/3 15:53
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    IDUserService idUserService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        DUser user = (DUser) principalCollection.getPrimaryPrincipal();
        //获取用户的角色和权限
//        authorizationInfo.addRole();
//        authorizationInfo.addStringPermissions();

        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("授权认证--->");
        String username = (String) authenticationToken.getPrincipal();

        DUser user = idUserService.getOne(new QueryWrapper<DUser>().eq("user_account",username));
        //salt 应该是从数据库取出来
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,user.getUserPassword(),ByteSource.Util.bytes(username),getName());


        return authenticationInfo;
    }
}
